#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <functional>
using namespace std;
void usage(void)
{
    cout << "Usage:\n\t"
         << "server ip port" << endl;
}
int main(int argc, char *argv[], char *envp[])
{
    if (argc != 3)
    {
        usage();
        exit(-1);
    }

    string ip = argv[1];
    uint16_t port = atoi(argv[2]);
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    int cnt = 5;
    while (0 != connect(sock, (struct sockaddr *)&server, sizeof(server)))
    {
        cout << "正在重新链接，重连次数还有：" << cnt-- << endl;
        sleep(1);
        if (cnt == 0)
        {
            cout << "链接失败" << endl;
            exit(-2);
        }
    }

    while (1)
    {
        cout << "input message:";
        string str;
        getline(cin, str);
        write(sock, str.c_str(), str.size());
        char buff[1024];
        int n = read(sock, buff,sizeof(buff) - 1);
        if (n > 0)
        {
            buff[n] = 0;
            cout << "server:" << buff << endl;
        }
        else if (n == 0)
        {
            cout << "对方把链接关闭" << endl;
            break;
        }
        else
        {
            cerr << "read error" << endl;
            exit(-3);
        }
    }

    return 0;
}